import { PageContainer } from '@ant-design/pro-layout';
import ProTable, { EditableProTable } from '@ant-design/pro-table';
import ProForm, { DrawerForm, ProFormText, ProFormSelect, ProFormDatePicker, ProFormTextArea, ProFormRadio } from '@ant-design/pro-form';
import React, { useState, useRef } from 'react';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import { Popconfirm,Button,message, InputNumber, Input, Upload, Modal, Select } from 'antd';
import { PlusOutlined, UploadOutlined } from '@ant-design/icons';
import { manufacturerOption, newUUID,isImageType, moneyFormat } from '@/utils/utils';
import WHProductChoose from '@/components/Common/WHProductChoose';
import { ProductType } from '@/model';
import ProductChoose from '@/components/Common/ProductChoose';
import {addVolumeAndDetails,getVolumeList,removeVolume,getVolumeAndDetails,removeVolumeDetail,updateVolume,getDearHosDeptList,deptList} from '../../pages/StockIO/service';

import request from '@/utils/request';
import { Row } from 'antd';
import { Col } from 'antd';
import UpDownLabel from './UpDownLabel';
import AccountDialog from './AccountDialog';
const { confirm } = Modal;

export type PutOutProps = {
  cust:number;
};
const DealerSaleUpload: React.FC<PutOutProps> = (props)=>{
const [showCreate, setShowCreate] = useState(false);
const [accoutDialog, setAccountDialog] = useState(false);
const actionRef = useRef<ActionType>();
const [detail, setDetail] = useState<any>({});
const [hadTicket, setHadTicket] = useState(true);
const [editableKeys, setEditableRowKeys] = useState<React.Key[]>([0]);
const [proData, setProData] = useState<any>([]);
const [previewVisible,setPreviewVisible] =  useState(false);
const [previewImage,setPreviewImage] =  useState('');
const [hospitalId,setHospitalId] =  useState<any>('');

const [fileList,setFileList] = useState<any>([]);
const [newFileList,setNewFileList] = useState<any>([]);
const [shipId,setShipId] = useState('');
const [reasonFlag, setReasonFlag] = useState(1);
const [volumeType, setVolumeType] = useState(0);
const formRef = useRef<any>();
const [buyList,setBuyList] = useState<any>([]);
const [proModalVisible, setProModalVisible] = useState(false);
const [pIndex, setPindex] = useState<number>(0);
const [proVisible, setProVisible] = useState(false);
const [editFlag, setEditFlag] = useState(true);
const [ocrLoading,setOcrLoading] = useState(true);
const [detps,setDetps] = useState<any>([]);
const [showFlag,setShowFlag] = useState(false);
const dealerFlag = (sessionStorage.getItem('access') as string).indexOf('jxs')>=0 || (sessionStorage.getItem('access') as string).indexOf('dealer')>=0;

const outColumns: ProColumns[] = [{
    title: '厂家',
    dataIndex: 'manufacturer',
    valueType: 'select',
    ellipsis:true,
    valueEnum: manufacturerOption(),
    width: 50,
    editable: false
  }, {
    title: '产品名称',
    width: 60,
    ellipsis:true,
    dataIndex: 'product_name',
    editable: false
  }, {
    width: 60,
    ellipsis:true,
    title: '产品型号',
    dataIndex: 'product_standard',
    editable: false
  }, {
    title: '批号',
    dataIndex: 'batch',
    width:  80,
    formItemProps: (form, {
        rowIndex
      }) => {
        return {
          rules: [{
            required: true,
            message: '出库数量必填'
          }]
        };
      },
      renderFormItem: (_:any, {
        type,
        defaultRender,
        formItemProps,
        fieldProps,
        record,
        ...rest
      }, form) => {
        return <Input {...fieldProps} disabled={proData[_.index].isInventory==='1'}  placeholder='请输入'/>;
      }
  },  {
    width: 50,
    title: '数量',
    dataIndex: 'nowNumbs',
    formItemProps: (form, {
      rowIndex
    }) => {
      return {
        rules: [{
          required: true,
          message: '出库数量必填'
        }]
      };
    },
    renderFormItem: (_, {
      type,
      defaultRender,
      formItemProps,
      fieldProps,
      ...rest
    }, form) => {
      return <InputNumber {...fieldProps} placeholder='请输入' min={0} precision={0}/>;
    }
  },{
    width: 70,
    title: '单价(不含税元)',
    dataIndex: 'money',
    valueType: 'money',
    formItemProps: (form, {
      rowIndex
    }) => {
      return {
        rules: [{
          required: true,
          message: '单价必填'
        }]
      };
    }
  }, {
    title: '总价(元)',
    editable: false,
    width:60,
    dataIndex: 'price',
    valueType: 'money',
    renderText: (_, record: any) => {
      var val = record.money * Math.abs(record.nowNumbs);
      return val;
    }
  },
  {
    title: '采购科室',
    width:100,
    hideInTable:props.cust==2,
    ellipsis:true,
    dataIndex: !showFlag?'dept':'deptName',
    renderFormItem: (_:any, {
      type,
      defaultRender,
      formItemProps,
      fieldProps,
      ...rest
    }, form) => {
      let deptFlag =proData[_.index].volume_level==='1'
      return deptFlag?<Select {...fieldProps} placeholder='请选择' defaultValue={proData[_.index].dept}   options={detps}/>:<></>;
    }
  }
  , {
    title: '操作',
    valueType: 'option',
    fixed:'right',
    width: 50,
    render: () => {
      return null;
    }
  }];

const allDept = async()=>{
  var val = await deptList({current:1,pageSize:200})
  if (val.errorCode === '200') {
    setDetps(val.data.map((item:any)=>{return {label:item.name,value:item.id}}))
  }
}
const edit = async(flag:boolean,record:any)=>{
  //获取下医院对应的科室
  var val =undefined
  if(record.customerType==='1'&&record.volumeType==="1"){
      val = await getDearHosDeptList({
        customerId: record.hospitalId,
      });
    if (val.errorCode === '200') {
      setDetps(val.data.map((item:any)=>{return {label:item.name,value:item.id}}))
   }
  }else if(record.volumeType==="2"){
    allDept()
  }
  setShowFlag(!flag)

  var val =await getVolumeAndDetails({volumeId:record.volumeId})
  if(val.errorCode==='200'){
    setNewFileList([])
    setDetail(val.data.volume)
    val.data.attachments.forEach((element:any) => {
      element.name = element.attName;
      element.url = element.attPath;
      element.uid = element.id;
      element.serverFlag = true
    });
    //初始化下附件
    setFileList(val.data.attachments)
    //初始化下产品
    var pIndex = 0
    var pArray = val.data.details.map((item:any)=>{
      pIndex++
      return {
        'pIndex':pIndex,
        'manufacturer':item.manufacturer,
        'product_name':item.productName,
        'product_standard':item.productStandard,
        'batch':item.productBatch,
        'nowNumbs':item.volumeNum,
        'money':item.price,
        'productId':item.productId,
        'inventoryId':item.inventoryId,
        'volumeId':item.volumeId,
        'isInventory':item.isInventory,
        'volumeDetailId':item.volumeDetailId,
        'dept':item.hospitalDeptId,
        'deptName':item.hospitalDeptName,
        'volume_level':item.volumeLevel
      }
    })
    setProData(pArray)
    setPindex(pIndex);
    setHadTicket(record.isBill==='1')
    setShipId(record.shipId)
    setEditableRowKeys(pArray.map((item: any) => item.pIndex));
    setShowCreate(true)
    setEditFlag(flag)
  }else{
    message.error('获取报量详情失败')
  }
}

// React.useEffect(()=>{
//   setTimeout(()=>{
//     console.log('222222',requestCount)
//     if(requestCount==0){
//     }
//     actionRef.current?.reloadAndRest?.();

//   },1000)
//   return function cleanup() {};
// },[]);


const columns: ProColumns[] = [
  {
    title:'客户代码',
    dataIndex:'dealerCode',
    width:80,
  },
  {
      title:'客户名称',
      dataIndex:'dealerName',
      width:120,
      ellipsis:true,
  },
   {
       title:'购买方代码',
       dataIndex:'hospitalCode',
       width:80,
   },
   {
        title:'购买方名称',
        dataIndex:'hospitalName',
        width:120,
        ellipsis:true,
    },
    {
      title:'上报日期',
      dataIndex:'createTime',
      hideInSearch:true,
      width:100,
     },
     {
      title:'更新日期',
      dataIndex:'updateTime',
      hideInSearch:true,
      width:100,
     },
    {
      title:'报量方式',
      dataIndex:'volumeType',
      valueType:'select',
      width:60,
      valueEnum:{
          '1' : {text:'授权'},
          '2' : {text:'非授权'},
          }
      },
    {
      title:'是否开票',
      dataIndex:'isBill',
      valueType:'select',
      width:60, 
      valueEnum:{
          '1' : {text:'有'},
          '0' : {text:'无'},
      }
   },
   {
    title:'发票代码',
    dataIndex:'billCode',
    hideInSearch:true,
    width:80,
   },
   {
    title:'发票号码',
    dataIndex:'billNumber',
    width:80,
},
   {
    title:'发票日期',
    dataIndex:'date2',
    valueType:'dateRange',
    hideInTable:true,
    width:80,
   },
    {
      title:'发票日期',
      dataIndex:'billDate',
      hideInSearch:true,
      width:80,
    },
    {
      title:'上报日期',
      dataIndex:'date1',
      hideInTable:true,
      width:100,
      valueType:'dateRange',
     },
    {
        title:'总价(不含税)',
        valueType:'money',
        dataIndex:'volumeTotalPrice',
        hideInSearch:true,
        width:120,
    },
   {
    title:'操作',
    valueType:'option',
    width:100,
    fixed: 'right',
    render: (text, record:any, _, action) => [
       <a key='detail' onClick={async () => {
        edit(false,record)
       }}>详情</a>,
       <a  key='edit' onClick={async ()=>{
        edit(true,record)
     }} hidden={checkEdit(record)}>修改</a>,
       <Popconfirm  title='确定要删除吗?' key='delete' onConfirm={() => handleDelete(record.volumeId)}><a hidden={checkEdit(record)}>删除</a></Popconfirm>
    ]}
   ]
   const handleDelete = async(id:string) => {
        var val = await removeVolume({
          volumeId: id,
        });

       if (val.errorCode === '200') {
           message.success('作废成功')
           actionRef.current?.reloadAndRest?.()
       } else {
          message.error(val.errorMessage)
       }
   };

   const checkEdit = (record:any)=>{
      if(!dealerFlag){
        return true
      }
      if(record.isEditable==='0'){
        return true
      }
      return false
   }

const uploadProps = {
    multiple: false,
    name: 'file',
    accept:'image/*,application/pdf',
    action: '/xwyl/attachment/uploadAttach',
    headers: {
      authorization: 'authorization-text',
    },
    beforeUpload:(file: any, FileList: any[])=>{
      var flag =  file.type.indexOf('image/')>=0||file.type.indexOf('pdf')>=0;
      if(!flag){
         message.error('请上传图片格式或pdf格式')
      }
      return flag;
    }
  };

  const requestAccount=async(volumeType:number)=>{
    setVolumeType(volumeType)

  }

  const handlePreview=async(file:any)=>{
    
    if(file.url){
        // setPreviewImage(file.url);
        window.open(file.url);
    }else{
        // setPreviewImage(file.attPath);
        window.open(file.attPath);
    }
    // setPreviewVisible(true);
  };

  const getReason=()=>{
    if(detail.noBillReason=='1'){
      return '区域收费原因(一直不能开票)'
    }
    if(detail.noBillReason=='1'){
      return '尚未开票(后期会开出发票)'
    }
    return '两票制原因'
  }

  const getBillType=()=>{
    if(detail.billType=='1'){
      return '一级客户(在直接订货的)'
    }
    if(detail.billType=='2'){
      return '二级客户(从一级客户拿货的)'
    }
    return '托管公司/配送公司'
  }

  const getDepts=async(id:string,clear:boolean,name:string)=>{
    var val = await getDearHosDeptList({
      customerId: id,
    });
   if (val.errorCode === '200') {
      setDetps(val.data.map((item:any)=>{return {label:item.name,value:item.id}}))
      if(clear){
        setProData([])
      }
      formRef?.current?.setFieldsValue({"hospitalName":name});
      setHospitalId(id)

   } else {
      message.error(val.errorMessage)
   }
  }

  const initAdd=(flag:number)=>{
    setShipId(newUUID());
    setOcrLoading(false)
    setDetps([])
    setEditFlag(true);
    setHadTicket(true);
    setShowCreate(true);
    setDetail(undefined);
    setNewFileList([])
    requestAccount(flag);
    setFileList([]);
    setProData([])
    setShowFlag(false)
    if(flag==2){
      allDept()
    }
  }

return (<PageContainer>
    <ProTable actionRef={actionRef} headerTitle='列表' columns={columns} pagination={{pageSizeOptions: ['20', '100', '500']}}
       scroll={{x: 1800}}  request={(params, sorter, filter) => {
        if(params.date1){
            params.createTimeBegin=params.date1[0];
            params.createTimeEnd=params.date1[1];
            params.date1=undefined;
        }
        if(params.date2){
          params.billDateBegin=params.date2[0];
          params.billDateEnd=params.date2[1];
          params.date2=undefined;
        }
        params.customerType=props.cust;
        return getVolumeList({...params,filter})
    }} rowKey='volumeId' toolbar={{settings: []}}
       search={{span: 6}} toolBarRender={() => dealerFlag?[<Button type='primary' key='primary' onClick={() => {initAdd(1)}}>{props.cust==1?'授权医院报量':'授权客户报量'}</Button>,<Button type='primary' hidden={props.cust==2} key='second' onClick={() => {initAdd(2)}}>非授权医院报量</Button>]:[]}
   />
  <DrawerForm submitter={editFlag?{}:{
            render: (props, defaultDoms) => {
              return [];
            },
          }} formRef={formRef} title={detail ? '' : '新增'} width="1200" onVisibleChange={setShowCreate} visible={showCreate} drawerProps={{forceRender: true,destroyOnClose: true}} 
  onFinish={async (values: any) => {
    var val = undefined
    if(!detail){
      if(newFileList.length==0){
        message.warning('请上传附件！');
        return false
      }
    }
    //构造下产品
    if(proData.length==0){
      message.warning('请先选择报量的产品！');
      return false
    }
    for(var i=0;i<proData.length;i++){
      var item = proData[i] 
      if(!item.batch||!item.nowNumbs){
        message.warning('请填写产品的批号、数量');
        return false
      }
      if(props.cust!=2&&item.volume_level==='1'&&!item.dept){
        message.warning('请选择产品对应的科室');
        return false
      }
    }
    values.details = proData.map((item:any)=>{
      var v:any =  {
        manufacturer:item.manufacturer,
        productId:item.productId,
        productName:item.product_name,
        productStandard:item.product_standard,
        productUnit:item.packing_unit,
        productBatch:item.batch,
        inventoryId:item.inventoryId,
        isInventory:item.isInventory,
        volumeNum:item.nowNumbs,
        price:item.money,
        volumeDetailId:item.volumeDetailId,
        hospitalDeptId:item.dept,
        totalPrice:item.money * Math.abs(item.nowNumbs)
      }
      if(item.dept){
        v.hospitalDeptName=detps.filter((s:any)=>s.value===item.dept)[0].label
      }
      return v
    })
    if (detail) {
      values.volumeId = detail.volumeId;
      val = await updateVolume(values);
    } else {
      //构造非产品的数据
      if(hadTicket){  
        if(values.InvoiceNum.length!=8){
          message.warning('发票号码必须为8位')
          return false;
        }
        values.billCode = values.InvoiceCode
        values.billNumber = values.InvoiceNum
        values.billDate = values.InvoiceDate
        values.volumeTotalPrice = values.TotalAmount
        values.billCompany =values.SellerName
        values.billPurchaseName = values.PurchaserName

      }else{
        //不开票
        values.noBillReason = reasonFlag

      }
      values.hospitalId = hospitalId
      values.isDelete = '0'
      values.shipId = shipId
      values.customerType = props.cust
      values.volumeType = volumeType
      values.isBill = hadTicket?'1':'0'
     val = await addVolumeAndDetails(values);
    }
    if (val.errorCode === '200') {
      message.success('提交成功');
      actionRef.current?.reloadAndRest?.();
      return true;
    } else {
      message.error(val.errorMessage);
      return false;
    }
  }}>
      {
        !detail?
        <>
          <ProForm.Group>
              <ProFormText name='name' label='客户名称' readonly initialValue={sessionStorage.getItem('loginName')}  placeholder=''/>
              <ProFormText name='hospitalName' width="md" rules={[{required: true}]} label='购买方名称' readonly   placeholder='请选择购买方'/><Button 
              onClick={()=>{setAccountDialog(true)}}
              type="primary" key="choose">选择购买方</Button>
        </ProForm.Group>
          <ProForm.Group>
          <ProFormRadio.Group name='isBill' label='是否开票'
              fieldProps={{value: hadTicket?'1':'0',onChange:(v:any)=>{
                  setHadTicket(v.target.value==='1')
              }}}
              width={330}  options={[{value:'1',label:'是'},{value:'0',label:'否'}]}/>
        </ProForm.Group>

        </>
      :
      <>
         <Row>
              <Col span={6}><UpDownLabel title='客户名称' texts={[detail.dealerName]}></UpDownLabel></Col>
              <Col span={6}><UpDownLabel title='客户名称' texts={[detail.hospitalName]}></UpDownLabel></Col>
              <Col span={6}></Col>
          </Row>
          <Row>
            <Col span={6}><UpDownLabel title='是否开票' texts={[detail.isBill==='1'?'是':'否']}></UpDownLabel></Col>
          </Row>
          {detail.isBill==='1'?
           <>
            <Row>
              <Col span={6}><UpDownLabel title='发票代码' texts={[detail.billCode]}></UpDownLabel></Col>
              <Col span={6}><UpDownLabel title='发票号码' texts={[detail.billNumber]}></UpDownLabel></Col>
              <Col span={6}><UpDownLabel title='发票日期' texts={[detail.billDate]}></UpDownLabel></Col>
              <Col span={6}><UpDownLabel title='产品不含税总金额' texts={[moneyFormat(detail.volumeTotalPrice)]}></UpDownLabel></Col>
            </Row>

            <Row> 
              <Col span={6}><UpDownLabel title='票面销售方名称' texts={[detail.billCompany]}></UpDownLabel></Col>
              <Col span={6}><UpDownLabel title='票面销售方类型' texts={[getBillType()]}></UpDownLabel></Col>
            </Row>
            <Row> 
              <Col span={6}><UpDownLabel title='票面购买方名称' texts={[detail.billPurchaseName]}></UpDownLabel></Col>
              <Col span={12}><UpDownLabel title='票面购买方类型(是否托管公司/配送公司)' texts={[detail.isTrusteeship==='0'?'否':'是']}></UpDownLabel></Col>
            </Row>
           </>:
            <>
            <Row>
              <Col span={12}><UpDownLabel title='无法开票原因' texts={[getReason()]}></UpDownLabel></Col>
            </Row>
           </>
          }
      </>
      }
      
      <p hidden={detail?true:hadTicket?false:true} className="ant-upload-hint" style={{color:'#ff0000'}}>建议直接上传图片格式的发票照片可自动识别相关信息，如照片模糊无法识别需要手动填写</p>
      <div hidden={detail?false:true} className="ant-upload-hint" style={{fontSize:16,fontWeight:700}}>附件</div>
      <Upload  {...uploadProps} onPreview={handlePreview} fileList={fileList} disabled={!editFlag}
                onRemove={(record:any)=>{
                  if(record.serverFlag){
                    message.warning('已有附件不可删除')
                    return;
                  }
                  confirm({
                    content: '确定删除吗？',
                    onOk:async()=> {
                      var req = request('/xwyl/attachment/deleteAtt', {
                        method: 'POST',
                        requestType:'form',
                        data: {
                          ...{id:record.uid},
                          method: 'post',
                        },
                      });
                      var val =await req;
                      if(val.errorCode==='200'){
                        var newList=fileList.filter((item:any)=>{
                          return item.uid!=record.uid;
                        });
                        setFileList(newList)
                      }else{
                        message.error('删除失败');
                      }
                    },
                    onCancel() {
                      console.log('Cancel');
                    },
                  });
                }}
                onChange={async(info:any)=>{
                  if (info.file.status === 'done') {
                    if(info.file.response.errorCode==='200'){
                      if(!detail){
                        var list:any[] = newFileList;
                        message.success(`${info.file.name}上传成功`);
                        var data = info.file.response.data;
                        data.uid = data.attId;
                        data.name = info.file.name;
                        data.url = data.location;
                        data.status ='done';  
                        list.push(data);
                        setNewFileList([...list]);
                      }else{
                        var list:any[] = fileList;
                        message.success(`${info.file.name}上传成功`);
                        var data = info.file.response.data;
                        data.uid = data.attId;
                        data.name = info.file.name;
                        data.url = data.location;
                        data.status ='done';  
                        list.push(data);
                        setFileList([...list]);
                      }
                     
                    }else{
                      message.error(`${info.file.name} 上传失败.`);
                    }
                  } else if (info.file.status === 'error') {
                    message.error(`${info.file.name} 上传失败.`);
                  }
                }}   data={{'shipId':shipId,'userId':sessionStorage.getItem('userId')}} headers={{
                  'authorization':`${sessionStorage.getItem('token')}`}}>
                <Button hidden={!editFlag?true:false} icon={<UploadOutlined />}><span style={{color:'red'}}>*</span>{hadTicket?'上传发票':'上传附件'}</Button>
                <span style={{color:'red'}} hidden={!hadTicket}>【1个发票号码只能上传对应的发票附件，其他发票号码及对应发票附件请另外提交上报】</span>
              </Upload>
              {
                newFileList.map((item:any,index:number)=>{
                  var _index = item.name.lastIndexOf('.') // 获取指定字符串最后一次出现的位置，返回index
                  var str = item.name.substr(_index + 1) 
                  return <div style={{display:'flex',paddingTop:10,alignItems:'center'}}>
                    {hadTicket?<Button hidden={!isImageType(str)} loading={ocrLoading} type="primary" key={'ocr_'+index} onClick={async()=>{
                         if(ocrLoading){
                           return;
                         }
                         setOcrLoading(true)
                          var req = request('/xwyl/billOcr/billOcrContent?billUrl='+item.url, {
                            method: 'POST',
                            requestType:'form'
                          });
                          var val = await req
                          if(val.errorCode==='200'){
                            formRef.current?.setFieldsValue({...val.data})
                            if(val.data.SellerName==sessionStorage.getItem('loginName')){
                                formRef.current?.setFieldsValue({billType:sessionStorage.getItem('level')})
                            }
                          }else{
                            message.error('OCR失败失败！')
                          }
                          setOcrLoading(false)
                    }}>发票OCR自动识别</Button>:<></>}
                    <a style={{flex:1,marginLeft:20}} onClick={()=>{
                      handlePreview(item)
                    }}>{item.name}</a>
                    <Button key={'del_'+index} onClick={()=>{
                        confirm({
                          content: '确定删除吗？',
                          onOk:async()=> {
                            if(fileList.length==1){
                              message.warning('请先上传新的附件，再删除')
                              return;
                            }
                            var req = request('/xwyl/attachment/deleteAtt', {
                              method: 'POST',
                              requestType:'form',
                              data: {
                                ...{id:item.uid},
                                method: 'post',
                              },
                            });
                            var val =await req;
                            if(val.errorCode==='200'){
                              var newList=newFileList.filter((subitem:any)=>{
                                return item.uid!=subitem.uid;
                              });
                              setNewFileList(newList);
                            }else{
                              message.error('删除失败');
                            }
                          },
                          onCancel() {
                            console.log('Cancel');
                          },
                        });
                    }}>删除</Button>
                  </div>
                })
              }
        {!detail?
          <>
             <div style={{height:20}}></div>
       <ProForm.Group>
           {hadTicket? 
           <>
           <ProFormText fieldProps={{maxLength:12}} name='InvoiceCode' label='发票代码'  placeholder='请输入发票代码' width={150} initialValue={detail?.allName} rules={[{required: true}]} />
           <ProFormText fieldProps={{maxLength:8}} name='InvoiceNum' label='发票号码'  placeholder='请输入发票号码' width={150} initialValue={detail?.shortName} rules={[{required: true}]} />
           <ProFormDatePicker name='InvoiceDate' label='发票日期' placeholder='请选择发票日期' width={150}  rules={[{required: true}]}></ProFormDatePicker>
           <ProFormText name='TotalAmount' label='产品不含税总金额' placeholder='请输入不含税总金额' width={150} rules={[{required: true}]} ></ProFormText>
           </>
           :<></>}
       </ProForm.Group>
           {hadTicket?
           <>
            <ProForm.Group>
              <ProFormText name='SellerName' label='票面销售方名称'  placeholder='请输入票面销售方名称' width='sm' rules={[{required: true}]} />
              <ProFormSelect  name='billType' label='票面销售方类型' placeholder='请选择票面销售方类型' width='sm' rules={[{required: true}]}  options={[{label:'一级客户(在直接订货的)',value:'1'},{label:'二级客户(从一级客户拿货的)',value:'2'},{label:'托管公司/配送公司',value:'3'}]}/>
            </ProForm.Group>
            <ProForm.Group>
              <ProFormText name='PurchaserName' label='票面购买方名称'  placeholder='请输入票面购买方名称' width='sm'/>
              <ProFormSelect name='isTrusteeship' label='票面购买方类型(是否托管公司/配送公司)'  initialValue={''} hidden={props.cust==2}
            rules={[{required: props.cust==1}]} options={[{value:'1',label:'是'},{value:'0',label:'否'}]}/>
            </ProForm.Group>
           </>:
                <ProForm.Group>
           <div  key='tab2'>
          <ProFormRadio.Group name='noBillReason' label='无法开票原因' fieldProps={{
          value: reasonFlag,
          onChange: v => {
            setReasonFlag(v.target.value);
          }
        }} initialValue={reasonFlag} options={[{
          label: '区域收费原因(一直不能开票)',
          value: 1
        }, {
          label: '尚未开票(后期会开出发票)',
          value: 2
        }, {
          label: '两票制原因',
          value: 3
        }]}/>
            <span style={{
          color: '#f10000'
        }}>温馨提示：<br/>
【一直不能开票的】<br/>注1：未开票必须上传产品使用证明：（例如外壳包装、术中条形码贴纸等）<br/>
【后期会开出发票的】<br/>注2：需要上传①配送商/托管公司销售给医院的发票（如有） 或者②客户销售给配送商/托管公司的发票+出库单、产品使用证明（例如外壳包装、 术中条形码贴纸等）+商务部线下核查（如需）</span><br/><br/>

</div></ProForm.Group>
           }


       <div style={{color:'#f10000'}} hidden={!hadTicket}>
       若票面购买方类型选择“是”，需在【上传发票】处上传证明文件，如：出库单、外壳包装、术中条形码等。
                </div>

                <div style={{marginTop:20}}>
            <ProFormTextArea name='volumeRemark' label='备注' placeholder='请输入备注' fieldProps={{showCount:true,maxLength:200}} />
          </div>
          </>
          :
          <>
            <div style={{height:20}}></div>  
            <Row>
              <Col span={24}><UpDownLabel title='备注' texts={[detail.volumeRemark]}></UpDownLabel></Col>
            </Row>
          </>
        }

        <div style={{marginLeft:-20}}>
        <EditableProTable  headerTitle={<>
            <span>报量产品列表</span><span style={{color:'#ff0000',fontSize:14,marginLeft:30}}>若上报非库存产品销量，将经由相关部门审核销量真实性！</span>
        </>} rowKey='pIndex' columns={outColumns} value={proData} search={false} toolbar={{
            settings: []
        }} recordCreatorProps={false} onChange={data => {
            setEditableRowKeys(data.map((item: any) => item.pIndex));
            setProData(data);
        }} toolBarRender={() => editFlag?[<Button type='primary' key='primary' onClick={() => {
          setProModalVisible(true)
        }}>
          <PlusOutlined/>库存产品
         </Button>,<Button type='primary' key='primary' onClick={() => {
            setProVisible(true)
          }}>
                <PlusOutlined/>非库存产品
            </Button>]:[]} pagination={false} editable={editFlag?{
            editableKeys,
            type: 'multiple',
            deletePopconfirmMessage:'确定要删除改产品吗？',
            onChange: setEditableRowKeys,
            onDelete:async(v,record)=>{
                //调用删除
                if(record.volumeDetailId!=undefined){
                 var val = await removeVolumeDetail({volumeDetailId:record.volumeDetailId})
                  if (val.errorCode === '200') {
                    message.success('删除成功');
                    return true;
                  } else {
                    message.error('删除失败');
                    return false;
                  }
                } 
            },
            onValuesChange: (record, recordList) => {
              setProData(recordList);
            },
            actionRender: (row, config, defaultDoms) => {
              
            return [defaultDoms.delete];
            }
        }:{
          editableKeys:[],
          type: 'single',
        }}></EditableProTable>
        </div>
	  </DrawerForm>
    <WHProductChoose onCancel={() => {
      setProModalVisible(false);
    }} onSubmit={async (value: ProductType[]) => {
      var index = pIndex;
      value.forEach((v:any) => {
        index++;
        v.nowNumbs = 0;
        v.inventoryId=v.id
        v.money = 0;
        v.pIndex = index;
        v.isInventory = '1'
      });
      setPindex(index);
      setProModalVisible(false);
      var data = [...proData, ...value];
      setEditableRowKeys(data.map((item: any) => item.pIndex));
      setProData(data);
    }} modalVisible={proModalVisible} values={[]} status={1}/>
     <ProductChoose
            onCancel={() => {
              setProVisible(false)
            }}
            onSubmit={async (value:ProductType[]) => {
              var mIndex=pIndex;
              value.forEach((v:any)=>{
                mIndex++;
                v.pIndex=mIndex;
                v.inventoryId=''
                v.productId = v.id
                v.nowNumbs = 0;
                v.money = 0;
                v.isInventory = '0'
              })
              setPindex(mIndex);
              setProVisible(false);
              var data:any = [...proData,...value];
              setEditableRowKeys(data.map((item:any)=>item.pIndex));
              setProData(data);
              console.log(data)
            }}
             modalVisible={proVisible}
         />
        <Modal
            visible={previewVisible}
            width={1000}
            footer={null}
            onCancel={()=>setPreviewVisible(false)}
           >
          <img style={{ width: '100%' }} src={previewImage} />
        </Modal>
        <AccountDialog
            cust={props.cust}
            onCancel={() => {
              setAccountDialog(false)
            }}
            volumeType={volumeType}
            onSubmit={async (value:any) => {
              setAccountDialog(false)
              if(props.cust===2){
                setHospitalId(value[0].hospitalId)
                formRef.current.setFieldsValue({"hospitalName":value[0].hospitalName});
                return;
              }
              if(volumeType==2){
                setHospitalId(value[0].hospitalId)
                formRef.current.setFieldsValue({"hospitalName":value[0].hospitalName});
                return;
              }
              //判断上一次的id和e是否相同，如果不相同，并且产品不为空，则弹出提示是否清空
              var lastId = hospitalId;
              if(lastId&&lastId!==value[0].hospitalId&&proData.length>0){
                confirm({
                  content: '切换医院，产品需重新选择，确定要切换吗？',
                  onOk:async()=> {
                    getDepts(value[0].hospitalId,true,value[0].hospitalName)
                  },
                  onCancel() {
                    
                  },
                });
              }else{
                getDepts(value[0].hospitalId,false,value[0].hospitalName)
              }
   
            }}
            modalVisible={accoutDialog}
           >
        </AccountDialog>
   </PageContainer>
)
}
export default DealerSaleUpload;